//
//  WifiUploadController.swift
//  Reader
//
//  Created by MN on 2023/11/1.
//

import UIKit
import Alamofire

class WifiUploadController: UIViewController {
    var localHttpServer:HTTPServer!
    var message:UILabel!
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        localHttpServer.stop()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white;
        message = UILabel(frame: CGRect(x: 0, y: NavgationBarHeight, width: ScreenWidth, height: ScreenHeight-NavgationBarHeight-TabBarHeight))
        message.font = UIFont.systemFont(ofSize: 30, weight: .bold)
        message.textAlignment = .center
        message.numberOfLines = 0;
        view.addSubview(message)
        testNet()
        self.setupLocalHttpServer()
       
    }
    func testNet() {
        let re = Alamofire.request(ApiUrl.baidu, method: HTTPMethod.get)
                re.response { res in
//                    print(res);
                }
    }
    func setupLocalHttpServer() {
        localHttpServer = HTTPServer.init()
        localHttpServer.setType("_http.tcp")
      
        guard  let bundlePath = Bundle.main.resourcePath else{
            print("error")
            return
        }
        let webPath = bundlePath + "/web"
        localHttpServer.setDocumentRoot(webPath)
        localHttpServer.setConnectionClass(MyHTTPConnection.classForCoder())
        self.startServer()
    }
    func startServer() {
        do {
            try localHttpServer.start()
            let port = localHttpServer.listeningPort()
            if let ip = self.getWifiIP() {
                let string = "http://\(ip):\(port)"
                message.text = "在电脑浏览器输入\n" + string + "\n已经复制在粘贴板"  + "\n网页打开传输中，请勿关闭页面"
                UIPasteboard.general.string = string
            }
            
        } catch let err {
            print("error \(err)")
        }
        
    }
        
        
    //获取本机无线局域网ip
    func getWifiIP() -> String? {
            
           var address: String?
           var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
           guard getifaddrs(&ifaddr) == 0 else {
               return nil
           }
           guard let firstAddr = ifaddr else {
               return nil
           }
            
           for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
               let interface = ifptr.pointee
               // Check for IPV4 or IPV6 interface
               let addrFamily = interface.ifa_addr.pointee.sa_family
               if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
                   // Check interface name
                   let name = String(cString: interface.ifa_name)
                   if name == "en0" {
                       // Convert interface address to a human readable string
                       var addr = interface.ifa_addr.pointee
                       var hostName = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                       getnameinfo(&addr,socklen_t(interface.ifa_addr.pointee.sa_len), &hostName, socklen_t(hostName.count), nil, socklen_t(0), NI_NUMERICHOST)
                       address = String(cString: hostName)
                   }
               }
           }
            
           freeifaddrs(ifaddr)
           return address
       }
}

enum ApiUrl:String {
    case baidu = "https://www.cnblogs.com/ybw123321/p/5359911.html"
}

extension ApiUrl: URLConvertible {
    
    /// Returns a `URL` if `self` can be used to initialize a `URL` instance, otherwise throws.
    ///
    /// - Returns: The `URL` initialized with `self`.
    /// - Throws:  An `AFError.invalidURL` instance.
    public func asURL() throws -> URL {
        
        guard let url = URL(string: self.rawValue) else { throw AFError.invalidURL(url: self) }
        
        return url
    }
}

